package test.com.qu.myapplication.service;

import android.app.Application;
import android.content.Context;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

/**
 * Created by Administrator on 2017/3/14.
 */

public class App extends Application{
    private static App Instance;
    @Override
    public void onCreate() {
        super.onCreate();
        Instance = this;
        //初始化网络请求
        Api.init(Instance);
    }

    public static App getInstance(){
        return Instance;
    }
    /**
     *
     读取app_config目录下的config
     */
    public Properties get() {
        FileInputStream fis = null;
        Properties props = new Properties();
        try {
            // 读取files目录下的config
            // fis = activity.openFileInput(APP_CONFIG);

            // 读取app_config目录下的config
            File dirConf = Instance.getDir("config", Context.MODE_PRIVATE);
            fis = new FileInputStream(dirConf.getPath() + File.separator
                    + "config");
            /**读取文件，以键值对的形式来保存在Properties对象中*/
            props.load(fis);
        } catch (Exception e) {
        } finally {
            try {
                fis.close();
            } catch (Exception e) {
            }
        }
        return props;
    }

    /**
     * 设置Properties
     * @param p
     */
    private void setProps(Properties p) {
        FileOutputStream fos = null;
        try {
            // 把config建在(自定义)app_config的目录下
            File dirConf = Instance.getDir("config", Context.MODE_PRIVATE);
            File conf = new File(dirConf, "config");
            fos = new FileOutputStream(conf);
            /**保存文件*/
            p.store(fos, null);
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (Exception e) {
            }
        }
    }

    public void set(String key, String value) {
        Properties props = get();
        props.setProperty(key, value);
        setProps(props);
    }
    public String get(String key) {
        Properties props = get();
        return (props != null) ? props.getProperty(key) : null;
    }
}
